package org.embedchat.protocol.codec.server;

import java.io.DataInputStream;
import java.io.IOException;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import org.embedchat.protocol.Constants;
import org.embedchat.protocol.codec.AbstractMessageDecoder;
import org.embedchat.protocol.message.AbstractMessage;
import org.embedchat.protocol.message.server.ErrorMessage;

public class ErrorMessageDecoder extends AbstractMessageDecoder {

	public ErrorMessageDecoder() {
		super(Constants.ERROR_MESSAGE);
	}

	@Override
	protected AbstractMessage decodeBody(IoSession session, ByteBuffer in, long bodyLength) {
        if (in.remaining() < bodyLength) {
            return null;
        }
        ErrorMessage m = new ErrorMessage();
        DataInputStream is = null;
        try {
            is = new DataInputStream(in.asInputStream());
            m.setMessageCode(is.readInt());
            m.setErrorMessageString(is.readUTF());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return m;
	}

	public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception {
	}
}
